/*
 * Copyright 2007-2009 Perttu "celeron55" Ahola <celeron55@gmail.com>
 *
 * This file is part of jukumagic.
 *
 * jukumagic is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * jukumagic is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with jukumagic.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "common.h"
#include "flistbox.h"
#include "jukuapp.h"

#include <iostream>

IMPLEMENT_DYNAMIC_CLASS(FListBox, wxListBox)

BEGIN_EVENT_TABLE(FListBox, wxListBox)
	EVT_RIGHT_UP(FListBox::OnRightUp)
    EVT_CHAR(FListBox::OnChar)
    EVT_KEY_DOWN(FListBox::OnKeyDown)
    EVT_KEY_UP(FListBox::OnKeyUp)
END_EVENT_TABLE()

DEFINE_EVENT_TYPE(wxEVT_FLISTBOX_NUMBER_INPUT)

void FListBox::ResetNumberInput()
{
	m_numbers_to_take = 1;
	m_numbers_token = 0;
	m_number = 0;
}

FListBox::FListBox()
: wxListBox()
{
}

FListBox::FListBox(wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize)
: wxListBox(parent, id, pos, size, 0, NULL, wxLB_SINGLE)
{
}

FListBox::~FListBox()
{
}

void FListBox::OnRightUp(wxMouseEvent& event)
{
	event.Skip();
}

void FListBox::OnChar(wxKeyEvent &event)
{
	int keycode = event.GetKeyCode();
	if(keycode < '0' || keycode > '9'){
		event.Skip();
		return;
	}
	int newnumber = keycode - '0';
	if(newnumber == 0 && m_numbers_token == 0){
		m_numbers_to_take++;
		return;
	}
	m_number += newnumber * pow(10, m_numbers_to_take - (++m_numbers_token));
	if(m_numbers_token >= m_numbers_to_take){
		SetSelection(m_number-1);
		wxCommandEvent event(wxEVT_FLISTBOX_NUMBER_INPUT, GetId());
		event.SetEventObject(this);
		event.SetInt(m_number);
		GetEventHandler()->ProcessEvent(event);
		ResetNumberInput();
	}
}

void FListBox::OnKeyDown(wxKeyEvent &event)
{
	wxUint32 keycode = event.m_keyCode;
	switch(keycode)
	{
	case WXK_ESCAPE:
		ResetNumberInput();
		break;
	default:
		event.Skip();
	}
}

void FListBox::OnKeyUp(wxKeyEvent &event)
{
	wxUint32 keycode = event.m_keyCode;
	switch(keycode)
	{
	case WXK_BACK:
		wxGetApp().m_frame->FocusFootprintSearch();
		break;
	default:
		event.Skip();
	}
}

void FListBox::SetFootprints(std::vector<Footprint*> &footprints)
{
	Clear();
	int a = 1;
	for(std::vector<Footprint*>::iterator i = footprints.begin();
			i != footprints.end(); i++){
		Footprint *f = (Footprint*)(*i);
		wxString s;
		for(int b = 10; b <= a; b *= 10) s << wxT("0");
		s << a << wxT(": ") << f->m_name;
		if(f->m_subname.Length() > 0) s << wxT(" (") << f->m_subname << wxT(")");
		Append(s);
		a++;
	}
	ResetNumberInput();
}


